package tech.mhuang.pacebox.springboot.autoconfiguration.trace.okhttp;

import com.alibaba.fastjson.JSON;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import tech.mhuang.pacebox.core.exception.ExceptionUtil;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * okhttp埋点拦截
 *
 * @author mhuang
 * @since 1.0.0
 */
public class TraceOkHttpInterceptor implements Interceptor {

    private static final String COMPONENT_NAME = "okhttp";
    private Tracer tracer;
    private Pattern skipPattern;

    public TraceOkHttpInterceptor(Tracer tracer) {
        this.tracer = tracer;
    }

    public TraceOkHttpInterceptor(Tracer tracer, Pattern skipPattern) {
        this.tracer = tracer;
        this.skipPattern = skipPattern;
    }

    protected boolean isTraced(Request request) {
        if (skipPattern != null) {
            String url = request.url().toString();
            return skipPattern.matcher(url).matches();
        }

        return false;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (isTraced(request)) {
            return chain.proceed(request);
        }
        Span span = tracer.buildSpan(request.method())
                .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)
                .start();
        Tags.COMPONENT.set(span, COMPONENT_NAME);
        span.setTag("request.header", JSON.toJSONString(request.headers()));
        span.setTag("request.body", JSON.toJSONString(request.body()));
        span.setTag("request.url", request.url().toString());
        span.setTag("request.param", request.url().query());
        try {
            Response response = chain.proceed(request);
            Tags.HTTP_STATUS.set(span, response.code());
            span.setTag("response", JSON.toJSONString(response.body()));
            return response;
        } catch (IOException e) {
            Tags.ERROR.set(span, Boolean.TRUE);
            Map<String, String> log = ExceptionUtil.logsForException(e);
            log.put("event", Tags.ERROR.getKey());
            span.log(log);
            throw new IOException(e);
        } finally {
            span.finish();
        }
    }
}
